package com.springboot.mall.filter;



import com.springboot.mall.common.Constant;
import com.springboot.mall.model.entity.User;
import com.springboot.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/*
 *管理员校验过滤器
 *
 *@data 2022-05-10
 */
public class AdminFilter implements Filter {
    @Autowired
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    //还未进入controller进行拦截过滤的操作
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //从这里面拿到request
        HttpServletRequest request= (HttpServletRequest)servletRequest;
        //再获得session
        HttpSession session = request.getSession();
        User currentUser = (User)session.getAttribute(Constant.USER);
        if (currentUser  == null){
            //这个方法返回的是void，所以不能返回ApiRestResponse
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10007,\n" +
                    "    \"msg\": \"NEED_LOGIN\",\n" +
                    "    \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
            //这个return表示如果没登陆下面的判断是否是管理员就没必要运行了
            return;
        }
        //校验是否是管理员
        boolean adminRole = userService.checkAdminRole(currentUser);
        if (adminRole){
            //是管理员
            //一下操作应该是一个抽象的操作：放行
            //进入到下一个过滤器
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10009,\n" +
                    "    \"msg\": \" NEED_ADMIN\",\n" +
                    "    \"data\": null\n" +
                    "}");
            out.flush();
            out.close();

        }

    }

    @Override
    public void destroy() {

    }
}
